var express = require('express');
var router = express.Router();
var http = require('http').Server(router);
var io = require('socket.io')(http);
var config = require("../config.json");
/*数据库*/
var mysql = require('mysql');
var bodyParser = require("body-parser");
var pool = mysql.createPool(config.mysql);


var connectNum = config.customer.maxConnectNUm; //客服最大连接数
// 房间用户名单
var roomInfo = {

};
//初始化room名单
for (var i = 0; i < connectNum; i++) {
	roomInfo["room_" + i] = [];
}
io.on('connection', function(socket) {
	var roomID = ""; // 获取房间ID
	var user = {};
	socket.on('join', function(obj) {
		for (var key in roomInfo) {
			if (roomInfo[key].length < 1) { //检验房间人数是不是大于2,自动分配房间
				roomID = key;
				break;
			}
		}

		user = obj;
		roomInfo[roomID].push(user);
		socket.join(roomID); // 加入房间

		// 通知房间内人员
		io.to(roomID).emit('login', {
			user: user.name,
			msg: "您好"
		}, roomInfo[roomID]);
		console.log(user.name + '加入了' + roomID);
		console.log(roomInfo)

	});

	socket.on('kefu', function(obj) {
		roomID = "kefu";
		roomInfo[roomID] = [];
		socket.join(roomID); // 加入房间
		roomInfo[roomID].push(obj);

		// 通知房间内人员
		io.to(roomID).emit('login', {
			user: obj.name,
			msg: "您好",
			roomArr: roomInfo
		}, roomInfo[roomID]);
		console.log('我是客服');
	});
	socket.on('chating', function(obj, roomid) {
		console.log('我开始了');
		roomID = roomid;
		roomInfo[roomID] = [];
		socket.join(roomID); // 加入房间
		roomInfo[roomID].push(obj);
		// 通知房间内人员
		io.to(roomID).emit('login', {
			user: obj.name,
			msg: "客服进来服务了",
			roomArr: roomInfo
		}, roomInfo[roomID]);

	});

	socket.on('leave', function() {
		socket.emit('disconnect');
	});

	socket.on('disconnect', function() {
		// 从房间名单中移除
		var index = roomInfo[roomID].indexOf(user);
		if (index !== -1) {
			roomInfo[roomID].splice(index, 1);
		}
		socket.leave(roomID); // 退出房间
		io.to(roomID).emit('login', {
			msg: user.name + "离开了"
		}, roomInfo[roomID]);
		console.log(user + '退出了' + roomID);
	});

	// 接收用户消息,发送相应的房间
	socket.on('talk', function(msg) {
		console.log("i sayid here");
		console.log(roomID);
		io.to(roomID).emit('talk', msg);
	});

});


http.listen(8080, function() {
	console.log('chart start');
});
//登陆接口
router.get('/login', function(req, res, next) {
	pool.getConnection(function(err, connection) {
		var user_name = "'" + req.query.name + "'";
		var user_password = "'" + req.query.password + "'";
		var sql = "select name ,id from chat_mum where user =" + user_name + " and password =" + user_password;
		console.log(sql);
		connection.query(sql, function(err, rows, fields) {
			if (err) {
				console.log(err);
			}
			if (rows.length == 1) {
				var json = {
					code: 200,
					obj: rows
				}
				res.send(json);
			} else {
				var json = {
					code: 400,
					obj: "账号或密码错误"
				}
				res.send(json);
			}
			connection.release();
		})

	})
})
module.exports = router;